;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Stock.ForwardAllotApply", [])
        .controller("ForwardAllotApplyCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "Upload", "$timeout", "EventBus", "$filter", "$stateParams", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, UserContextService, Upload, $timeout, EventBus, $filter, $stateParams) {
            $scope.activeFlag = [true, false, false, false, false, false];
            $scope.datePickerFlag = [false, false];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                curRow: -1
            };
            $scope.submitted = false;
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.warehouseCode={};
            $scope.condition = {
                createStatusList:[],
                createStatusStr:''
            };
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.allotTypeList = [];
            $scope.dataList = [];
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/forwardAllotApply/export"),
                sectionParam: {ids: []},
                allUrl: ybHttp.RequestUrl("device", "/forwardAllotApply/exportAll")
            };
            var materielFieldListForAdd = [
                {
                    name: "零件编号",
                    width: 300,
                    dataField: "materialsNo",
                    needInput: false
                },
                {
                    name: "零件中文名",
                    width: 300,
                    dataField: "materialsDes",
                    needInput: false
                },
                {
                    name: "申请数量",
                    width: 300,
                    dataField: "applyQty",
                    needInput: true,
                    needRequired: true
                },
                {
                    name: "备注",
                    width: 300,
                    dataField: "remark",
                    needInput: true,
                }
            ];
            var materielFieldListForAddView = [
                {
                    name: "零件编号",
                    width: 300,
                    dataField: "materialsNo",
                    needInput: false
                },
                {
                    name: "零件中文名",
                    width: 300,
                    dataField: "materialsDes",
                    needInput: false
                },
                {
                    name: "申请数量",
                    width: 300,
                    dataField: "applyQty",
                    needInput: true,
                    needRequired: true
                },
                {
                    name: "已建区域调拨单数量",
                    width: 300,
                    dataField: "createQty",
                    needInput: false
                },
                {
                    name: "备注",
                    width: 300,
                    dataField: "remark",
                    needInput: false
                },
                {
                  name: "标准交期",
                  width: 150,
                  dataField: "standDeliveryTime",
                  isShow: true,
                },
                {
                    name: "预计发货日期",
                    dataField: "estimatedShippingDateShow",
                    width: 130,
                    isShow: true,
                },
            ];
            $scope.orderObj = {
                headerInfo: {},
                materialList: []
            };
            $scope.stateList = [{
                    code: 0,
                    name: '草稿'
                },
                {
                    code: 1,
                    name: '待审核'
                },
                {
                    code: 2,
                    name: '已审核'
                },
                {
                    code: 3,
                    name: '审核驳回'
                }
            ];
            $scope.tableConfig = {
                fixedWidth: 200,
                scrollWidth: 2400,
                tableCol: [
                    {
                        type: "",
                        name: "单据编号",
                        dataField: "billNo",
                        width: 170,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "供货商名称",
                        dataField: "supplierOrgName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请机构名称",
                        dataField: "applyOrgName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "状态",
                        dataField: "statusShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建状态",
                        dataField: "createStatusShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "供货商出库仓库编号",
                        dataField: "outWarehouseCode",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "供货商入库仓库编号",
                        dataField: "inWarehouseCode",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建人名称",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建时间",
                        dataField: "createDateShow",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "更新人名称",
                        dataField: "updateNameShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "更新时间",
                        dataField: "auditDateShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核人名称",
                        dataField: "auditName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核时间",
                        dataField: "auditDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核信息",
                        dataField: "auditMessage",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "remark",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调度员",
                        dataField: "dispatcherName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: $scope.isEN ? 610 : 500,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };

            $scope.materielTableConfig = {
                scrollWidth: 1390,
                tableCol: []
            };
            $scope.tabFlag = {
                name: ''
            };

            var btnPermissionCode = {
                ApplicationForWard: window.ActionCode.ApplicationForWard,
                FinishApply: window.ActionCode.FinishApply,
            };

            $scope.btnPermission = {
                ApplicationForWard: true,
                FinishApply:true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }
            // $scope.searchAddress = function () {
            //     ybWidget.SelectDeliveryAddress({
            //         deliveryName: $scope.curUser.name,
            //         clientReceiveInfo: $scope.onlySelect,
            //         supplierOrgId: $scope.curOrg.orgId
            //     }).then(function (data) {
            //         $scope.orderObj.headerInfo.receiveUser = data.receiverName;
            //         $scope.orderObj.headerInfo.receiveTel = data.receiverTel;
            //         $scope.orderObj.headerInfo.receiveAddress = data.receiverAddress;
            //     });
            // };
            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    }
                };
            };
            $scope.checkDate = function (item, start, end) {
                if ((angular.isUndefined(item[start]) || !item[start]) && (angular.isUndefined(item[end]) || !item[end])) {
                    return;
                }
                if (!!item[start] && (angular.isUndefined(item[end]) || !item[end])) {
                    item[start] = ybWidget.FormatStartDate(item[start]);
                    return;
                }
                if ((angular.isUndefined(item[start]) || !item[start]) && !!item[end]) {
                    item[end] = ybWidget.FormatEndDate(item[end]);
                    return;
                }
                var tmpTime = item[start];
                if (item[end] < item[start]) {
                    item[start] = ybWidget.FormatStartDate(item[end]);
                    item[end] = ybWidget.FormatEndDate(tmpTime);
                } else {
                    item[start] = ybWidget.FormatStartDate(item[start]);
                    item[end] = ybWidget.FormatEndDate(item[end]);
                }
            };
            $scope.selectSupplier = function () {
                var param = {
                    name: "主机厂名称",
                    type: "supplier"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    console.log(data)
                    $scope.orderObj.headerInfo.supplierOrgName = data.companyName
                    $scope.orderObj.headerInfo.supplierOrgId = data.supplierOrgId
                    $scope.orderObj.headerInfo.outWarehouseCode = ''
                    $scope.orderObj.materialList = []
                    $scope.orderObj.headerInfo.dispatcherName = ''
                    $scope.orderObj.headerInfo.dispatcherId = ''
                    getOutStore(data.supplierOrgId);
                })
            };
            // 查询机构下的仓库
            function getOutStore(supplierOrgId) {
                var reqUrl = "/companyDealer/list";
                var param = {
                    pageSize: 10,
                    pageNum: 1,
                    filters: {
                        orgId: supplierOrgId,
                        dealerOrgId: $scope.orderObj.headerInfo.applyOrgId
                    }
                };
                ybHttp.Post('device', reqUrl, param).then(function (resp,param) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    console.log('tttt',resp)
                    //去除默认选中
                    $scope.warehouseCode = resp.value.list[0]?.forwardWarehouseCode;
                    if(!$scope.warehouseCode){
                        //直接不给做单据 杜洪刚
                        ybWidget.ShowMessage('请先设置前移仓库，当前无法创建单据！');
                    }
                });
            }
            $scope.searchDispatch = function () {
                if (!$scope.orderObj.headerInfo.supplierOrgId) {
                    ybWidget.ShowToaster('error', '请先选择主机厂名称');
                    return;
                }
                var param = {
                    name: "区域调拨调度员",
                    defaultRoleName: '',
                    type: 'staffByWorkspace',
                    supplierOrgId: $scope.orderObj.headerInfo.supplierOrgId
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.headerInfo.dispatcherName = data.name;
                    $scope.orderObj.headerInfo.dispatcherId = data.userId;
                })
            }
            $scope.clearSupplier = function() {
                // 主机厂选择数据清空
                $scope.orderObj.headerInfo.supplierOrgName = ''
                $scope.orderObj.headerInfo.supplierOrgId = ''
                $scope.orderObj.headerInfo.outWarehouseCode =  ''
                $scope.orderObj.headerInfo.inWarehouseCode =  ''
                $scope.orderObj.headerInfo.dispatcherName = ''
                $scope.orderObj.headerInfo.dispatcherId = ''
                $scope.orderObj.materialList = []
            }
            function initData() {
                $scope.tabFlag = {};
                $scope.detailInfo = {
                    crucialDevice: 0,
                    entranceDevice: 0
                };
                $scope.orderObj = {
                    headerInfo: {},
                    materialList: []
                };
                $scope.markInfo.allCheckedMaterial = false;
                $scope.toolbarConfig.showMateriel = false;
            }

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        getDataList();
                        $scope.submitted = false;
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    default:
                        break;
                }
            };

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                var service = "device";
                var reqUrl = "/forwardAllotApply/page";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                splitStatus();
                param.filters = $scope.condition;
                param.filters.billNoList =  param.filters.billNoList ?  ($filter("replaceN")(param.filters.billNoList)).split(',') : ''
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.updateNameShow = $filter("YbDate")(item.updateName, 'yyyy-MM-dd HH:mm:ss');
                        item.auditDateShow = $filter("YbDate")(item.auditDate, 'yyyy-MM-dd HH:mm:ss');
                        item.statusShow = $filter("ProgressStatus")(item.status, "applyOrgNameStatus");
                        item.createStatusShow = $filter("ProgressStatus")(item.createStatus, "createdStatus");
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                    return resp.value.list;
                });
            }

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.tdClick = function (item, fnType, type) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item, type);
                        break;
                    default:
                        break;
                }
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.switchDatePicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };
            $scope.reset = function () {
                $scope.condition = {
                    createStatusList:[],
                    createStatusStr:''
                };
            };
            function splitStatus() {
                if( $scope.condition.createStatusStr){
                    $scope.condition.createStatusList=$scope.condition.createStatusStr.split(",");
                }else{
                    $scope.condition.createStatusList=[];
                }
            }
            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            $scope.addApply = function () {
                $scope.tabFlag.type = 1;
                $scope.orderObj.headerInfo.createDate = +new Date();
                $scope.materielTableConfig.scrollWidth = 600;
                $scope.materielTableConfig.tableCol = materielFieldListForAdd;
                $scope.tabFlag.name = '新增'
                $scope.orderObj.headerInfo.applyOrgName = $scope.curOrg.companyName;
                $scope.orderObj.headerInfo.applyOrgId = $scope.curOrg.orgId;
                $scope.changeTab(2);
            };
            $scope.editApply = function (item) {
                $scope.tabFlag.name = '编辑'
                $scope.materielTableConfig.tableCol = materielFieldListForAddView
                $scope.materielTableConfig.tableCol[4].needInput = true
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj.headerInfo.statusShow = $filter("ProgressStatus")($scope.orderObj.headerInfo.status, "applyOrgNameStatus");
                    $scope.changeTab(2);
                });
            };
            $scope.finishApply = function (item) {
                ybWidget.ShowMessage("确认结单", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/forwardAllotApply/manualFinish";
                    console.log('item',item);
                    var param = {
                        id: item.id,
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                });
            };
            $scope.selectWarehouse = function (type) {
                if (!$scope.orderObj.headerInfo.supplierOrgId) {
                    ybWidget.ShowToaster('error', '请先选择主机厂名称');
                    return;
                }
                ybWidget.WarehouseUsingUserSelector({
                    param: $scope.orderObj.headerInfo.supplierOrgId,
                    needPermit: true,
                    reqUrl :"/warehouse/listOrgWarehouse"
                }).then(function (data) {
                    $scope.orderObj.headerInfo.outWarehouseCode = data.warehouseCode;
                })
            };
            $scope.selectInWarehouse = function () {
                if (!$scope.orderObj.headerInfo.supplierOrgId) {
                    ybWidget.ShowToaster('error', '请先选择主机厂名称');
                    return;
                }
                ybWidget.WarehouseUsingUserSelector({
                    param: $scope.orderObj.headerInfo.supplierOrgId,
                    needPermit: true,
                    reqUrl :"/warehouse/listOrgWarehouse",
                    warehouseCode:$scope.warehouseCode,
                    forwardAllotPage:true
                }).then(function (data) {
                    $scope.orderObj.headerInfo.inWarehouseCode = data.warehouseCode;
                })
            };
            $scope.clearWarehouse = function (type) {
                if (type == 'in') {
                    $scope.orderObj.headerInfo.inWarehouseCode = "";
                }
                if (type == 'out') {
                    $scope.orderObj.headerInfo.outWarehouseCode = "";
                }
            };

            $scope.clearLocCode = function () {
                angular.forEach($scope.orderObj.materialList, function (item) {
                    // 清除库区后同时清除默认储位
                    item.stockLocation = "";
                });
            }

            $scope.delApply = function (id) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/forwardAllotApply/remove?" + 'id=' + id;
                    ybHttp.Post(service, reqUrl).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };

            function getDetail(item) {
                var param = {
                    id: item.id
                };

                var reqUrl = '/forwardAllotApply/detail' // 正常查询详情
                return ybHttp.Get('device', reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    angular.forEach(resp.value.materialList, function (item) {
                        item.materialsDes = item.materialName;
                        item.materialsNo = item.materialNo;
                        item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    return $scope.orderObj = resp.value;
                });
            }


            $scope.auditBill = function (item) {
            };

            $scope.adjustBill = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    angular.forEach($scope.orderObj.materialList, function (item) {
                        item.deliveryNum = item.deliveryNum - item.amount;
                    });
                    $scope.changeTab(5);
                });
            };

            function viewDetail(item, type) {
                getDetail(item, type).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    $scope.materielTableConfig.tableCol = materielFieldListForAddView,
                    $scope.materielTableConfig.tableCol[2].needInput = false
                    $scope.materielTableConfig.tableCol[4].needInput =  false
                    $scope.orderObj.headerInfo.statusShow = $filter("ProgressStatus")($scope.orderObj.headerInfo.status, "applyOrgNameStatus");
                    $scope.changeTab(3);
                });
            }

            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    if (!$scope.orderObj.headerInfo.supplierOrgId) {
                        ybWidget.ShowToaster('error', '请先选择主机厂名称');
                        return;
                    }
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            $scope.importMateriel = function () {
                var param = {
                    name: "零件",
                    templateReqService: "device",
                    templateReqUrl: "/downloadFile/excelTemplate",
                    templateCondition: {
                        excelFileName: "ForwardAllotMaterialImport.xls"
                    },
                    importReqService: "device",
                    importReqUrl: "/forwardAllotApply/importMaterial",
                    importErrorUrl: "",
                    otherParams:{
                        supplierOrgId: $scope.orderObj.headerInfo.supplierOrgId,
                    }

                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                        item.materialsDes = item.materialName;
                        item.materialsNo = item.materialNo;
                    });
                    $scope.orderObj.materialList = [];
                    $scope.orderObj.materialList = angular.copy(data);
                });
            };

            $scope.delMateriel = function (item, index) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.orderObj.materialList.splice(index, 1);
                    EventBus.Publish("setMaterial", item.materialsNo);
                });
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.orderObj.materialList.length; i < len; i++) {
                    if (!!$scope.orderObj.materialList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.orderObj.materialList.length - 1; i >= 0; i--) {
                        if (!!$scope.orderObj.materialList[i].isChecked) {
                            if ((!!$scope.orderObj.materialList[i].inState && $scope.orderObj.materialList[i].inState !== 0) || (!!$scope.orderObj.materialList[i].outState && $scope.orderObj.materialList[i].outState !== 0)) {
                                ybWidget.ShowMessage("只能删除未调出的零件", MESG_TYPE.Warn);
                                return;
                            }
                            $scope.orderObj.materialList.splice(i, 1);
                        }
                    }
                    if ($scope.orderObj.materialList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");
                });
            };


            $scope.checkQtyForAdd = function (item) {
                item.qtyErr = false;
                if (!item.applyQty || parseFloat(item.applyQty) <= 0) {
                    item.qtyErr = true;
                    return;
                }
            };
            $scope.handleAudit = function(type, ids, msg) {
                var service = "device";
                var reqUrl = "";
                var param = {
                    id: ids,
                    passFlag: type == 1  ? 'true': 'false'
                };

                var msgStr = encodeURIComponent(msg);
                if (type == 1) {
                    // 通过
                    reqUrl = "/forwardAllotApply/audit?" + 'id='+ ids + '&' + 'passFlag=true' + '&' +'auditMessage=' + encodeURIComponent(msg)
                } else if (type == 2) {
                    // 拒绝
                    if (!msgStr) {
                        ybWidget.ShowMessage("请填写审核意见", MESG_TYPE.Error);
                        return
                    }
                    reqUrl = "/forwardAllotApply/audit?" + 'id='+ ids + '&' + 'passFlag=false' + '&' + 'auditMessage=' + encodeURIComponent(msg)
                }
                param.auditMessage = msgStr;
                console.log(param)
                console.log(reqUrl)
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                    $scope.changeTab(0);
                });
            };
            $scope.auditBillBatch = function (item) {
                ybWidget.AuditMsg({
                    passCb: function(val) {
                        return $scope.handleAudit(1, item.id, val)
                    },
                    refuseCb: function(val) {
                        return $scope.handleAudit(2, item.id, val)
                    }
                })
            };


            $scope.showQtyTip = function (item) {
                if (!!item.qtyStockErr) {
                    item.showStockErr = true;
                }
            };
            $scope.hideQtyTip = function (item) {
                item.showStockErr = false;
            };

            $scope.saveData = function (type, invalid) {
                if (!invalid) {
                    $scope.submitted = true;
                    return;
                }
                var listValid = true;
                var service = "device";
                var reqUrl = "/forwardAllotApply/add";


                for (var i = 0, len = $scope.orderObj.materialList.length; i < len; i++) {
                    $scope.orderObj.materialList[i].materialName = $scope.orderObj.materialList[i].materialsDes;
                    $scope.orderObj.materialList[i].materialNo = $scope.orderObj.materialList[i].materialsNo;
                    if (!$scope.orderObj.materialList[i].applyQty || parseFloat($scope.orderObj.materialList[i].applyQty) <= 0) {
                        listValid = false;
                        $scope.orderObj.materialList[i].qtyErr = true;
                        break;
                    }
                }
                if (!listValid) {
                    return;
                }
                if ($scope.orderObj.headerInfo.id) {
                    reqUrl = '/forwardAllotApply/update'
                }
                var param = angular.copy($scope.orderObj);
                param.submitFlag = type == 'save' ?  true : false,
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    $scope.activeFlag[2] = false
                });
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };


            $scope.clearDepot = function (item) {
                item.warehouseCode = "";
                item.areaCode = "";
                item.locationCode = "";
            };
            (function () {
                $scope.setFixedWidth();
                getDataList()
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }]);
})(window, window.angular);
